﻿using System;
using System.Linq;
using System.Web.Mvc;
using Solution.Business;
using Solution.Data;
using Solution.Utilities;
using Solution.Utilities.DynamicQueryable;
using System.Web;
using System.IO;
using Solution.Business.Infrastructure;

namespace Solution.Mvc.Areas.Admin.Controllers
{
    [Authorize]
    public class AtcArticleCPController : Controller
    {
        ArticleBLL Repository = new ArticleBLL();
        [CAuthorize(Module = "article", Functions = "V")]
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetData(bool? showBin, string sidx, string sord, int page, int rows)
        {
            bool _showBin = showBin ?? false;
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            var ccc = Repository.GetAll();//.Where(t => t.flag != "D").Count();
            int totalRecords = Repository.GetAll().Where(t => t.flag != "D").Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
            var questions = Repository.GetAll().Where(t => t.flag != "D").OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize).ToList();
            if (_showBin)
            {

                totalRecords = Repository.GetAll().Where(t => t.flag == "D").Count();
                totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
                questions = Repository.GetAll().Where(t => t.flag == "D").OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize).ToList();
            }
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = (from question in questions
                        select new
                        {
                            i = question.Id.ToString(),
                            cell = new string[] { 
                                question.Id.ToString(), 
                                question.Alias,
                                question.Name, 
                                question.Title,
                                question.User.FullName,
                                question.ShowComment.ToString(),
                                question.flag.ToString() }
                        }).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        [CAuthorize(Module = "article", Functions = "I,U,D")]
        public JsonResult Edit(string oper, bool? delForever, string[] id, string flag, FormCollection collection)
        {
            if (id != null)
            {
                string[] ids = id;
                bool _delForever = delForever ?? false;
                string Alias = ConvertUtility.ToString(collection["Alias"]);
                string[] Exception = { "-" };
                Alias = UtilCommon.VietNamese2English(Alias, false, true, Exception);
                Alias = Alias.Replace(" ", "-");
                string Name = ConvertUtility.ToString(collection["Name"]);
                string Title = ConvertUtility.ToString(collection["Title"]);
                bool ShowComment = ConvertUtility.ToBoolean(collection["ShowComment"]); ;

                switch (oper)
                {
                    case "add": return Json("err", JsonRequestBehavior.AllowGet);
                    case "del":
                        bool _flag = true;
                        foreach (var item in ids)
                        {
                            int Id = ConvertUtility.ToInt(item);
                            Article _entity = Repository.GetOne(Id);
                            if (_delForever)
                                Repository.Delete(_entity);
                            else
                            {
                                _entity.flag = "D";
                                if (!Repository.Update(_entity))
                                    _flag = false;
                            }
                        }
                        if (_flag)
                            return Json("ok", JsonRequestBehavior.AllowGet);
                        else
                            return Json("err", JsonRequestBehavior.AllowGet);
                    case "edit":
                        Article myfentity = Repository.GetOne(ConvertUtility.ToInt(ids[0]));
                        myfentity.Name = Name;
                        myfentity.Alias = Alias;
                        myfentity.Title = Title;
                        myfentity.ShowComment = ShowComment;
                        myfentity.flag = flag;
                        if (Repository.Update(myfentity))
                            return Json("ok", JsonRequestBehavior.AllowGet);
                        return Json("err", JsonRequestBehavior.AllowGet);
                    default:
                        return Json("err", JsonRequestBehavior.AllowGet);
                }

            }
            return Json("err", JsonRequestBehavior.AllowGet);
        }
        public ActionResult Create()
        {
            ViewBag.Categories = new CategoryBLL().GetAll().Where(p => p.flag != "D");
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        [CAuthorize(Module = "article", Functions = "I")]
        public ActionResult Create(string Name, string Alias, string Author, string Title, int CategoryId, bool ShowComment, string flag, HttpPostedFileBase ImageLink, string Lead, FormCollection collection)
        {
            ViewBag.Err = "";
            ViewBag.Categories = new CategoryBLL().GetAll().Where(p => p.flag != "D");
            string Detail = ConvertUtility.ToString(collection["Detail"]);
            Article entity = new Article();
            entity.Name = Name;
            entity.VersionId = 0;
            string[] Exception = { "-" };
            Alias = UtilCommon.VietNamese2English(Alias, false, true, Exception);
            Alias = Alias.Replace(" ", "-");
            entity.Alias = Alias;
            entity.Author = Author;
            entity.Title = Title;
            entity.CategoryId = CategoryId;
            entity.ShowComment = ShowComment;
            entity.Lead = Lead;
            entity.Detail = Detail;
            entity.PublishDate = DateTime.Now;
            entity.Created_Date = DateTime.Now;
            entity.Last_Modified_At = DateTime.Now;
            User _User = new UserBLL().GetOne(HttpContext.User.Identity.Name);
            entity.Created_By = _User.Id;
            entity.flag = flag;
            entity.ImageLink = "";
            if (ImageLink != null && ImageLink.ContentLength > 0)
            {
                try
                {
                    string filename = UtilCommon.UniqueName(ImageLink.FileName);
                    string pathThumb = "~/Content/Data/ArticleImg/Thumb/";
                    UtilCommon.ResizeAndSave(pathThumb, filename, ImageLink.InputStream, 160, true);
                    // System.IO.File.Delete(Server.MapPath(pathThumb + entity.ImageLink));
                    entity.ImageLink = filename;
                }
                catch
                {
                    ViewBag.Err = "Có lỗi xảy ra! Không lưu được hình ảnh";
                    return View();
                }
            }
            if (Repository.Insert(entity))
            {
                string url = Url.Content("~") + "admin/AtcArticleCP/";
                url = HttpUtility.UrlEncode(url);
                return Redirect("~/admin/success/?url=" + url);
            }
            else
            {
                ViewBag.Err = "Có lỗi xảy ra! kiểm tra lại trùng tên?";
                return View();
            }
        }

        public ActionResult EditAdvance(int Id)
        {
            ViewBag.Categories = new CategoryBLL().GetAll().Where(p => p.flag != "D");
            return View(Repository.GetOne(Id));
        }
        [HttpPost]
        [ValidateInput(false)]
        [CAuthorize(Module = "article", Functions = "U")]
        public ActionResult EditAdvance(int ID, string Alias, string Name, string Author, string Title, int CategoryId, bool ShowComment, string flag, HttpPostedFileBase ImageLink, string Lead, FormCollection collection)
        {
            // int ID = ConvertUtility.ToInt(collection["Id"]);
            // string Name = ConvertUtility.ToString(collection["Name"]);
            // int CategoryId = ConvertUtility.ToInt(collection["CategoryId"]);
            //string _ImageLink = ImageLink ?? "";
            // bool ShowComment = ConvertUtility.ToBoolean(collection["ShowComment"]);
            ViewBag.Err = "";
            ViewBag.Categories = new CategoryBLL().GetAll().Where(p => p.flag != "D");
            string Detail = ConvertUtility.ToString(collection["Detail"]);

            Article entity = Repository.GetOne(ID);
            entity.Name = Name;
            string[] Exception = { "-" };
            Alias = UtilCommon.VietNamese2English(Alias, false, true, Exception);
            Alias = Alias.Replace(" ", "-");
            entity.Alias = Alias;
            entity.Title = Title;
            entity.CategoryId = CategoryId;
            entity.ShowComment = ShowComment;
            entity.Author = Author;
            entity.Lead = Lead;
            entity.Detail = Detail;
            entity.flag = flag;
            if (ImageLink != null && ImageLink.ContentLength > 0)
            {
                try
                {
                    string filename = UtilCommon.UniqueName(ImageLink.FileName);
                    //string path = "~/Content/Data/ArticleImg/";
                    string pathThumb = "~/Content/Data/ArticleImg/Thumb/";
                    // UtilCommon.ResizeAndSave(path, filename, ImageLink.InputStream, 500, true);
                    UtilCommon.ResizeAndSave(pathThumb, filename, ImageLink.InputStream, 160, true);
                    string _oldLink = entity.ImageLink;
                    entity.ImageLink = filename;
                    System.IO.File.Delete(Server.MapPath(pathThumb + _oldLink));
                }
                catch
                {
                    ViewBag.Err = "Có lỗi xảy ra! Không lưu hoặc xóa được hình ảnh";
                }

            }
            if (Repository.Update(entity))
            {
                string url = Url.Content("~") + "admin/Atcarticlecp/";
                url = HttpUtility.UrlEncode(url);
                return Redirect("~/admin/success/?url=" + url);
            }
            else
            {
                ViewBag.Err = "Có lỗi xảy ra! kiểm tra lại trùng tên?";
                return View(Repository.GetOne(ID));
            }
        }
    }
}